//
//  SEGCompletePesonalInfoViewModel.m
//  SEGViewModel
//
//  Created by 乔杨 on 2020/6/9.
//

#import "SEGCompletePesonalInfoViewModel.h"

@implementation SEGCompletePesonalInfoViewModel

- (instancetype)init {
    self = [super init];
    if (self) {
        // 默认选值操作
        self.recordNickName = [SEGProfileManager sharedManager].profile.nickname;
        self.imagePath = [SEGProfileManager sharedManager].profile.ico;
        [self seg_createComtinueCommand];
        [self seg_createPassCommand];
        [self seg_createUploadImgCommand];
    }
    return self;
}
- (void)seg_createComtinueCommand {
    @weakify(self);
    self.comtinueCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(NSString *nick) {
        @strongify(self);
        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            if (self.imagePath.length <= 0) {
                NSError *error = [NSError errorWithDomain:@"" code:0 userInfo:@{NSLocalizedFailureReasonErrorKey:@"请上传头像"}];
                [subscriber sendError:error];
                return nil;
            }
            if ([nick stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]].length == 0) {
                NSError *error = [NSError errorWithDomain:@"" code:0 userInfo:@{NSLocalizedFailureReasonErrorKey:@"请输入昵称"}];
                [subscriber sendError:error];
                return nil;
            }
            NSString *nickname = nick;
            if ([nickname stringByReplacingOccurrencesOfString:@" " withString:@""].length <= 0) {
                NSError *error = [NSError errorWithDomain:@"" code:0 userInfo:@{NSLocalizedFailureReasonErrorKey:@"用户昵称不能为空"}];
                [subscriber sendError:error];
                return nil;
            }
            // 提交昵称的时候 去掉前后空格和回车
            nickname = [nickname stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
            // 记录上传的昵称
            self.recordNickName = nickname;
            // 保存接口要提交的数据
            [self seg_saveDataToUpdate];
            
            [subscriber sendNext:@""];
            [subscriber sendCompleted];
            return nil;
        }];
    }];
}
- (void)seg_createPassCommand {
    @weakify(self);
    self.passCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            @strongify(self);
            // 跳过的时候 拿回本来的昵称
            self.recordNickName = kAccountNickName;
            // 保存接口要提交的数据
            [self seg_saveDataToUpdate];
            
            [subscriber sendNext:@""];
            [subscriber sendCompleted];
            return nil;
        }];
    }];
}
- (void)seg_createUploadImgCommand {
    @weakify(self);
    self.uploadImgCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(UIImage *img) {
        @strongify(self);
        if (img.size.width * img.size.height > 102400) { // 是大图片，进行压缩
            self.imageData = [NSData dataWithData:UIImageJPEGRepresentation(img, 0.5)];
        } else {
            // 小图片，不压缩质量
            self.imageData = [NSData dataWithData:UIImageJPEGRepresentation(img, 1.0)];
        }
        //显示头像
        UIImage *ima = [UIImage imageWithData:self.imageData];
        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            [[SEGOnefileuploadManager sharedManager] requestOnefileuploadWithImage:ima progress:nil completed:^(BOOL isSuccessed, id result, NSString *codeType, NSError *error) {
                NSString *array = [result valueForKey:@"data"];
                if (!array || ![array isKindOfClass:[NSString class]]) {
                    [subscriber sendError:error];
                    return;
                }
                if (isSuccessed) {
                    NSString *imageStr = array;
                    SEGProfileModel *sysAccount = [SEGProfileManager sharedManager].profile;
                    sysAccount.ico = imageStr;
                    // 用户信息保存到本地
                    [SEGProfileManager seg_SaveSystemAccountWithUserID:sysAccount];
                    // 存储图片地址 -- 便于后续上传
                    self.imagePath = sysAccount.ico;
                    
                    [subscriber sendNext:ima];
                    [subscriber sendCompleted];
                } else {
                    [subscriber sendError:error];
                }
            }];
            
            return nil;
        }];
    }];
}

// 保存接口要提交的数据
- (void)seg_saveDataToUpdate {
    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *path = [doc stringByAppendingPathComponent:@"updateApartInfo.plist"];
    NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
    //  新增数据
    NSMutableDictionary *muDict = [NSMutableDictionary dictionaryWithDictionary:dict];
    [muDict setValue:self.recordNickName forKey:@"nickName"];
    [muDict setValue:self.imagePath forKey:@"imagePath"];
    dict = [NSDictionary dictionaryWithDictionary:muDict];
    // 新增数据存入文件
    [dict writeToFile:path atomically:YES];
}

#pragma mark - Getter
- (SEGMyManager *)myManager {
    if (!_myManager) _myManager = [[SEGMyManager alloc] init];
    return _myManager;
}

@end
